<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @selection-change="selectionChange"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="danger" size="small" @click="handleDelete" :disabled="!selectionList.length > 0">删除</el-button>
      </template>
      <template slot="menuRight">
        <el-button size="small" type="primary" @click="handleSetRules">ERP对账规则</el-button>
      </template>
      <template slot="menu" slot-scope="{ row }">
        <el-button type="text" icon="el-icon-view" size="small" v-if="permission.erpReconciliationRecord_view" @click="handleDetail(row)">详情 </el-button>
      </template>
    </avue-crud>

    <common-modal-template ref="commonModalTemplate" :option="modelOption" @getSelectedRows="getSelectedRows"></common-modal-template>
    <record-detail-dialog ref="detailDialog" :visibile.sync="detaiVisiable" :row-data="rowData"></record-detail-dialog>
    <!--   对账规则   -->
    <el-dialog title="ERP对账规则" :visible.sync="visiable" :append-to-body="true" @close="handleClose">
      <div class="sail-header-dialog-content">
        <avue-form ref="from" :option="formOption" v-model="form">
          <template slot-scope="{}" slot="checkType">
            <div class="form-content">
              <!--              <el-radio label="MANUAL" v-model="form.checkType" true-label="MANUAL">手动</el-radio>-->
              <div class="warehouse-option">
                <el-radio label="AUTO" v-model="form.checkType" true-label="AUTO">自动</el-radio>
              </div>
            </div>
          </template>
          <template slot-scope="{}" slot="dimension">
            <div class="form-content">
              <el-radio label="MATERIAL" v-model="form.checkDimensionality" true-label="MATERIAL">所有(物料)</el-radio>
              <div class="warehouse-option mt20">
                <el-radio label="INVENTORY" v-model="form.checkDimensionality" true-label="INVENTORY">仓库</el-radio>
                <div v-if="form.checkDimensionality === 'INVENTORY'" class="warehouse">
                  <label>仓库:</label>
                  <el-input placeholder="请选择 仓库" v-model="form.warehouseName" class="input-with-select" clearable @clear="form.areaIds = []">
                    <el-button slot="append" icon="el-icon-search" @click="openWarehouseModal"></el-button>
                  </el-input>
                </div>
              </div>
            </div>
          </template>
        </avue-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="handleSubmit"><i class="el-icon-circle-plus-outline"></i><span>保 存</span></el-button>
        <el-button size="small" @click="handleClose"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>
<script>
import { mapGetters } from 'vuex';
import RecordDetailDialog from '@/views/warehouse/components/recordDetailDialog';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getReconciliationRecordList, getReconciliationRule, removeReconciliationRecord, saveReconciliationRule } from '@/api/warehouse/erpReconciliation';
export default {
  name: 'erpReconciliationRecord',
  components: {
    RecordDetailDialog,
    CommonModalTemplate
  },
  watch: {
    'form.checkPeriod'(nval, oval) {
      if (nval !== oval) {
        this.form.checkDate = '';
      }
    }
  },
  data() {
    return {
      modelOption: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      rowData: {},
      detaiVisiable: false,
      data: [],
      selectionList: [],
      visiable: false,
      option: {
        calcHeight: 30,
        height: 'calc(100vh - 480px)',
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        delBtn: true,
        addBtn: false,
        searchShowBtn: false,
        refreshBtn: false,
        selection: true,
        indexLabel: '序号',
        columnBtn: false,
        column: [
          {
            label: '对账时间',
            type: 'datetimerange',
            prop: 'daterange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '时间日期开始范围',
            endPlaceholder: '时间日期结束范围',
            order: 1,
            hide: true,
            search: true,
            searchSpan: 7,
            searchType: 'datetimerange'
          },
          {
            label: '对账时间',
            prop: 'checkTime'
          },
          {
            label: '对账维度',
            prop: 'checkDimensionality',
            type: 'select',
            dicData: [
              { label: '物料', value: 'MATERIAL' },
              { label: '仓库', value: 'INVENTORY' }
            ]
          },
          {
            label: '对账笔数',
            prop: 'checkCount'
          },
          {
            label: '不相符笔数',
            prop: 'notMatchCount'
          },
          {
            label: '相符笔数',
            prop: 'matchCount'
          },
          {
            label: '对账方式',
            prop: 'checkType',
            type: 'select',
            dicData: [
              { label: '自动', value: 'AUTO' },
              { label: '手动', value: 'MANUAL' }
            ]
          }
        ]
      },
      formOption: {
        submitBtn: false,
        emptyBtn: false,
        group: [
          {
            label: '对账方式',
            arrow: false,
            icon: 'el-icon-vertical-bar',
            labelWidth: 50,
            column: [
              {
                label: '',
                prop: 'checkType',
                row: true,
                control: (val, form) => {
                  if (val === 'MANUAL') {
                    return {
                      checkPeriod: {
                        display: false
                      },
                      checkDate: {
                        display: false
                      },
                      checkTime: {
                        display: false
                      }
                    };
                  } else {
                    return {
                      checkPeriod: {
                        display: true
                      },
                      checkDate: {
                        display: true
                      },
                      checkTime: {
                        display: true
                      }
                    };
                  }
                }
              },
              {
                label: '自动对账周期',
                prop: 'checkPeriod',
                labelWidth: 150,
                type: 'select',
                dicData: [
                  {
                    label: '周',
                    value: 'WEEK'
                  },
                  {
                    label: '月',
                    value: 'MONTH'
                  },
                  {
                    label: '年',
                    value: 'YEAR'
                  }
                ],
                value: 'WEEK',
                row: true,
                control: (val, form) => {
                  if (val === 'WEEK') {
                    return {
                      checkDate: {
                        type: 'select',
                        dicData: [
                          { label: '星期一', value: '2' },
                          { label: '星期二', value: '3' },
                          { label: '星期三', value: '4' },
                          { label: '星期四', value: '5' },
                          { label: '星期五', value: '6' },
                          { label: '星期六', value: '7' },
                          { label: '星期日', value: '1' }
                        ]
                      }
                    };
                  } else if (val === 'MONTH') {
                    // 获取当前日期
                    const currentDate = new Date();
                    // 获取当前月份
                    const currentMonth = currentDate.getMonth();
                    // 获取当前年份
                    const currentYear = currentDate.getFullYear();
                    // 获取当月的天数
                    const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
                    // 生成当月日期数组对象
                    const monthDates = [];
                    for (let day = 1; day <= daysInMonth; day++) {
                      const label = `${day}日`;
                      const value = day;
                      monthDates.push({ label, value });
                    }
                    return {
                      checkDate: { dicData: monthDates, type: 'select' }
                    };
                  } else {
                    return {
                      checkDate: {
                        type: 'date',
                        valueFormat: 'yyyy-MM-dd',
                        format: 'yyyy-MM-dd'
                      }
                    };
                  }
                }
              },
              {
                label: '自动对账时间',
                prop: 'checkDate',
                labelWidth: 150,
                type: 'select',
                dicData: []
              },
              {
                label: '',
                prop: 'checkTime',
                type: 'time',
                valueFormat: 'HH:mm:ss',
                format: 'HH:mm:ss'
              }
            ]
          },
          {
            label: '对账维度',
            icon: 'el-icon-vertical-bar',
            arrow: false,
            border: false,
            labelWidth: 50,
            column: [
              {
                label: '',
                prop: 'dimension'
              }
            ]
          }
        ]
      },
      form: {
        warehouseName: '',
        checkType: 'AUTO',
        checkDimensionality: 'MATERIAL'
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.erpReconciliationRecord_view, false),
        delBtn: this.vaildData(this.permission.erpReconciliationRecord_del, false),
        addBtn: this.vaildData(this.permission.erpReconciliationRecord_add, false)
      };
    },
    ids() {
      return this.selectionList.map((i) => i.id).join(',');
    }
  },
  methods: {
    rowSave(row, done, loading) {},
    rowUpdate(row, index, done, loading) {},
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await removeReconciliationRecord({ ids: row.id });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          //　todo
          await removeReconciliationRecord({ ids: this.ids });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    beforeOpen(done, type) {},
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    async onLoad(page, params = {}) {
      this.loading = true;
      if (this.query.daterange) {
        this.query.startCheckTime = this.query.daterange[0];
        this.query.endCheckTime = this.query.daterange[1];
        delete this.query.daterange;
      }
      const { currentPage, pageSize } = this.page;
      try {
        const params = {
          ...this.query,
          current: currentPage,
          size: pageSize
        };
        const res = await getReconciliationRecordList(params);
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
      } catch (e) {
        console.warn(e);
      } finally {
        this.loading = false;
      }
    },
    async handleSetRules() {
      try {
        const res = await getReconciliationRule();
        const data = res.data.data || {};
        let areaNames = [];
        let areaIds = [];
        let form = {};
        if (data.relationList && data.relationList.length > 0) {
          data.relationList.forEach((item) => {
            areaIds.push(item.areaId);
            areaNames.push(item.areaName);
          });
        }
        this.form = {
          areaIds,
          warehouseName: areaNames.join(','),
          ...res.data.data
        };
        this.visiable = true;
      } catch (e) {
        console.warn(e);
      }
    },
    handleDetail(row) {
      this.$refs.detailDialog.getData(row.id);
      this.rowData = row;
      this.detaiVisiable = true;
    },
    getSelectedRows(rowData) {
      this.form.warehouseName = rowData.map((i) => i.name);
      this.form.areaIds = rowData.map((i) => i.id);
    },
    openWarehouseModal() {
      this.$refs.commonModalTemplate.showModal();
      this.modelOption = {
        modalTitle: '选择仓库',
        url: '/api/mes-admin/area/page/storage/management?areaType=WAREHOUSE',
        isPage: true,
        rowSelectionType: 'multiple',
        searchLabelWidth: 100,
        columnDefs: [
          {
            label: '仓库编码',
            prop: 'code',
            search: true
          },
          {
            label: '仓库名称',
            prop: 'name',
            search: true
          },
          {
            label: '仓库类型',
            prop: 'inventoryType',
            search: true,
            type: 'select',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=inventory_type'
          }
        ]
      };
    },
    async handleSubmit() {
      try {
        const params = this.getParams();
        const res = await saveReconciliationRule(params);
        this.$message.success('保存成功');
        this.visiable = false;
        this.onLoad(this.page);
      } catch (e) {
        console.warn(e);
      }
    },
    getParams() {
      let obj = {};
      const { checkType, checkDimensionality, checkDate = '', checkPeriod = '', checkTime = '', areaIds = [] } = this.form;
      obj.checkType = checkType;
      obj.checkDimensionality = checkDimensionality;
      if (checkType === 'AUTO') {
        obj.checkDate = checkDate;
        obj.checkPeriod = checkPeriod;
        obj.checkTime = checkTime;
      }
      checkDimensionality === 'INVENTORY' ? (obj.areaIds = areaIds) : '';
      return obj;
    },
    handleClose() {
      this.form = {
        warehouseName: '',
        checkType: 'MANUAL',
        checkDimensionality: 'MATERIAL'
      };
      this.visiable = false;
    }
  }
};
</script>
<style lang="scss" scoped>
.mt20 {
  margin-top: 20px;
}
.ml20 {
  margin-left: 20px;
}
.warehouse-option {
  display: flex;
  align-items: center;
  .warehouse {
    display: flex;
    label {
      width: 50px;
      display: block;
    }
  }
}
.input-with-select {
  width: 500px;
}
</style>
